package com.example.zhilierp.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.zhilierp.entity.Dept;
import com.example.zhilierp.service.DeptService;
import com.example.zhilierp.util.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 部门控制器
 * 处理部门相关的HTTP请求
 */
@RestController
@RequestMapping("/api/dept")
@Tag(name = "部门管理", description = "部门管理相关接口")
public class DeptController {

    @Autowired
    private DeptService deptService;

    /**
     * 分页查询部门列表
     * @param pageNum 页码
     * @param pageSize 每页数量
     * @param deptName 部门名称（可选）
     * @return 分页结果
     */
    @GetMapping("/page")
    @Operation(summary = "分页查询部门列表", description = "根据条件分页查询部门列表")
    public Result<Page<Dept>> page(@RequestParam(defaultValue = "1") Integer pageNum,
                                @RequestParam(defaultValue = "10") Integer pageSize,
                                @RequestParam(required = false) String deptName) {
        try {
            Page<Dept> page = new Page<>(pageNum, pageSize);
            Page<Dept> resultPage = deptService.page(page);
            return Result.success(resultPage);
        } catch (Exception e) {
            return Result.error(500, "查询部门列表失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID查询部门信息
     * @param id 部门ID
     * @return 部门信息
     */
    @GetMapping("/{id}")
    @Operation(summary = "根据ID查询部门信息", description = "根据部门ID获取详细信息")
    public Result<Dept> getById(@PathVariable Long id) {
        try {
            if (id == null) {
                return Result.error(400, "部门ID不能为空");
            }
            Dept dept = deptService.getById(id);
            if (dept == null) {
                return Result.error(404, "部门不存在");
            }
            return Result.success(dept);
        } catch (Exception e) {
            return Result.error(500, "查询部门信息失败: " + e.getMessage());
        }
    }

    /**
     * 新增部门
     * @param dept 部门信息
     * @return 操作结果
     */
    @PostMapping
    @Operation(summary = "新增部门", description = "创建新部门")
    public Result<Boolean> save(@RequestBody Dept dept) {
        try {
            if (dept == null) {
                return Result.error(400, "部门信息不能为空");
            }
            boolean success = deptService.insertDept(dept);
            return success ? Result.success(true) : Result.error(500, "新增部门失败");
        } catch (Exception e) {
            return Result.error(500, e.getMessage());
        }
    }

    /**
     * 修改部门
     * @param dept 部门信息
     * @return 操作结果
     */
    @PutMapping
    @Operation(summary = "修改部门", description = "更新部门信息")
    public Result<Boolean> update(@RequestBody Dept dept) {
        try {
            if (dept == null || dept.getId() == null) {
                return Result.error(400, "部门ID不能为空");
            }
            // 检查部门是否存在
            if (deptService.getById(dept.getId()) == null) {
                return Result.error(404, "部门不存在");
            }
            boolean success = deptService.updateDept(dept);
            return success ? Result.success(true) : Result.error(500, "修改部门失败");
        } catch (Exception e) {
            return Result.error(500, e.getMessage());
        }
    }

    /**
     * 删除部门
     * @param id 部门ID
     * @return 操作结果
     */
    @DeleteMapping("/{id}")
    @Operation(summary = "删除部门", description = "根据部门ID删除部门")
    public Result<Boolean> delete(@PathVariable Long id) {
        try {
            if (id == null) {
                return Result.error(400, "部门ID不能为空");
            }
            // 检查部门是否存在
            if (deptService.getById(id) == null) {
                return Result.error(404, "部门不存在");
            }
            boolean success = deptService.deleteDept(id);
            return success ? Result.success(true) : Result.error(500, "删除部门失败");
        } catch (Exception e) {
            return Result.error(500, e.getMessage());
        }
    }

    /**
     * 批量删除部门
     * @param ids 部门ID数组
     * @return 操作结果
     */
    @DeleteMapping("/batch")
    @Operation(summary = "批量删除部门", description = "批量删除多个部门")
    public Result<Boolean> deleteBatch(@RequestBody Long[] ids) {
        try {
            if (ids == null || ids.length == 0) {
                return Result.error(400, "部门ID数组不能为空");
            }
            boolean success = true;
            for (Long id : ids) {
                if (!deptService.deleteDept(id)) {
                    success = false;
                    break;
                }
            }
            return success ? Result.success(true) : Result.error(500, "批量删除部门失败");
        } catch (Exception e) {
            return Result.error(500, e.getMessage());
        }
    }

    /**
     * 获取部门树结构
     * @return 部门树
     */
    @GetMapping("/tree")
    @Operation(summary = "获取部门树结构", description = "获取系统所有部门的树状结构")
    public Result<List<Dept>> getDeptTree() {
        try {
            List<Dept> deptTree = deptService.getDeptTree();
            return Result.success(deptTree);
        } catch (Exception e) {
            return Result.error(500, "获取部门树失败: " + e.getMessage());
        }
    }

    /**
     * 检查部门名称是否唯一
     * @param deptName 部门名称
     * @param deptId 部门ID（编辑时使用）
     * @param parentId 父部门ID
     * @return 检查结果
     */
    @GetMapping("/checkDeptNameUnique")
    @Operation(summary = "检查部门名称是否唯一", description = "检查部门名称是否重复")
    public Result<Boolean> checkDeptNameUnique(@RequestParam String deptName,
                                           @RequestParam(required = false) Long deptId,
                                           @RequestParam Long parentId) {
        try {
            boolean isUnique = deptService.checkDeptNameUnique(deptName, deptId, parentId);
            return Result.success(isUnique);
        } catch (Exception e) {
            return Result.error(500, "检查部门名称失败: " + e.getMessage());
        }
    }

    /**
     * 更改部门状态
     * @param id 部门ID
     * @param status 状态：0禁用，1启用
     * @return 操作结果
     */
    @PutMapping("/status/{id}")
    @Operation(summary = "更改部门状态", description = "启用或禁用部门")
    public Result<Boolean> changeStatus(@PathVariable Long id, @RequestParam Integer status) {
        try {
            if (id == null) {
                return Result.error(400, "部门ID不能为空");
            }
            if (status == null || (status != 0 && status != 1)) {
                return Result.error(400, "状态值必须为0或1");
            }
            Dept dept = deptService.getById(id);
            if (dept == null) {
                return Result.error(404, "部门不存在");
            }
            dept.setStatus(status);
            boolean success = deptService.updateById(dept);
            return success ? Result.success(true) : Result.error(500, "更改部门状态失败");
        } catch (Exception e) {
            return Result.error(500, "更改部门状态失败: " + e.getMessage());
        }
    }
}